<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <th:block th:include="common/head::head"></th:block>
    <style>
        body {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }

        .console {
            height: 100%;
            position: relative;
        }

        .console .terminal {
            position: absolute;
            top: 40px;
            right: 0;
            bottom: 0;
            left: 0;
            border: 1px solid #c1c1c1;
            border-radius: 5px;
            font-family: Consolas;
            padding: 5px;
            overflow: auto;
            word-break: keep-all;
            white-space: nowrap;
        }

        .right {
            display: inline-block;
            float: right;
            margin-right: 10px;
        }


        .logSize, .status {
            line-height: 20px;
            padding: 9px 0;
            display: inline-block;
        }

        .status .status-div {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            border: 1px solid #c1c1c1;
        }

        .status .status-run {
            background-color: #05ff2d;
        }

        .status .status-stop {
            background-color: #ff0000;
        }

        .layui-form-switch {
            margin-top: 0 !important;
        }


    </style>
</head>

<body>
<div class="console">
    <form class="layui-form" action="">
        <div class="layui-row" id="optDiv" th:if="${manager}">
            <!-- layui-elem-quote -->
            <a href="javascript:;" class="btn-op layui-btn  layui-btn-sm" op="start">启动</a>
            <a href="javascript:;" class="btn-op layui-btn  layui-btn-sm layui-btn-warm" op="restart">重启</a>
            <a href="javascript:;" class="btn-op layui-btn  layui-btn-sm layui-btn-danger" op="stop">停止</a>

            <div th:if="${logSize}" class="layui-btn-group">

                <th:block th:if="${logSize?.get('logSize')}">
                    <a id="export" class="layui-btn layui-btn-sm">导出日志</a>
                </th:block>
                <a th:if="${logSize?.logBack}" id="logBack" class="layui-btn layui-btn-sm">备份列表</a>
            </div>

            <div class="status right">
                <div class="status-div"></div>
                <span></span>
            </div>


            <div class="right logDiv">
                <label class="layui-form-label">自动清屏</label>
                <input type="checkbox" checked name="autoClear" lay-skin="switch" lay-filter="autoClear"
                       lay-text="ON|OFF">
                <span class="logSize" id="logSize" th:if="${logSize?.get('logSize')}"
                      th:text="${logSize?.get('logSize')}">
                </span>
            </div>
        </div>
    </form>
    <div class="terminal"></div>
</div>
</body>
<script type="text/javascript">
    var loopLog = false;
    var loopLogTime;
    var heart;
    var nowStatus = false;

    var autoClearDom;
    var copyId = getQueryString("copyId");

    function loadSuccess() {
        // 处理按钮
        form.on('switch(autoClear)', function (data) {
            layui.data('cache', {
                key: "consoleAutoClear",
                value: this.checked
            });
        });
        const cache = layui.data('cache');
        autoClearDom = $("input[name='autoClear']");
        autoClearDom.attr('checked', cache.consoleAutoClear);
        form.render('checkbox');
        //
        const showLogDom = $('.console .terminal');
        if ('WebSocket' in window) {
            var url = getSocketHost() + "/console?userId=[[${session.user.getUserMd5Key()}]]&projectId=[[${projectInfo?.id}]]&nodeId=[[${node?.id}]]&type=console&copyId=" + copyId;
            const ws = new WebSocket(url);
            ws.onopen = function () {
                showLogDom.append('WebSocket连接成功！<br/>');
                setMsg('status');
            };

            ws.onmessage = function (data) {
                try {
                    var json_data = JSON.parse(data.data);
                    handleData(json_data);
                } catch (e) {
                    handleMsg(data.data);
                }
                scrollToBotomm();
            };

            ws.onclose = function (er) {
                // console.log(er)
                showLogDom.append('WebSocket连接已关闭！<br/>');
                clearInterval(loopLogTime);
                clearInterval(heart);
                $("#optDiv").hide();
                layer.alert("控制台已离线")
            };

            $('.btn-op').on('click', function () {
                var op = $(this).attr('op');
                if (op == "stop") {
                    layer.confirm("确定要停止该项目吗？", {
                        title: '系统提示'
                    }, function (index) {
                        layer.close(index);
                        setMsg(op);
                    });
                } else if (op == "restart") {
                    layer.confirm("确定要重启该项目吗？", {
                        title: '系统提示'
                    }, function (index) {
                        layer.close(index);
                        setMsg(op);
                    });
                } else {
                    setMsg(op);
                }
            });

            function handleMsg(msg) {
                showLogDom.append(msg + '<br/>');
                if (!loopLog && nowStatus) {
                    loopLogAjax();
                }
                clearInterval(heart);
                // 创建心跳，防止掉线
                heart = setInterval(function () {
                    const data = {
                        op: "heart",
                        projectId: "[[${projectInfo?.id}]]",
                        copyId: copyId
                    };
                    ws.send(JSON.stringify(data));
                }, 5000);
            }

            function handleData(json_data) {
                if (json_data.code !== 200) {
                    layer.msg(json_data.msg);
                }
                showLogDom.append(json_data.msg + (json_data.data || "") + '<br/>');
                var op = json_data.op;
                switch (op) {
                    case 'status':
                    case 'start':
                    case 'restart':
                        if (200 === json_data.code) {
                            $('.status .status-div').removeClass('status-stop').addClass('status-run');
                            $('.status span').text('运行中');
                            setOpBtn(false);
                            // 运行后需要实时加载日志
                            setMsg("showlog");
                        } else {
                            $('.status .status-div').removeClass('status-run').addClass('status-stop');
                            $('.status span').text(json_data.msg);
                            setOpBtn(true);
                            if (op == 'status') {
                                setMsg("showlog");
                            }
                        }
                        refreshProjectData();
                        break;
                    case 'stop':
                        if (200 === json_data.code) {
                            $('.status .status-div').removeClass('status-run').addClass('status-stop');
                            $('.status span').text('未运行');
                            setOpBtn(true);
                        } else {
                            $('.status span').text(json_data.msg);
                        }
                        refreshProjectData();
                        break;
                    case  'showlog':
                        break;
                    default:
                        break;
                }
            }

            function setMsg(opt) {
                const data = {
                    op: opt,
                    projectId: "[[${projectInfo?.id}]]",
                    copyId: copyId
                };
                layer.load(1, {
                    shade: [0.3, '#fff']
                });
                ws.send(JSON.stringify(data));
                setTimeout(function () {
                    layer.closeAll('loading');
                }, 2000);
            }
        } else {
            showLogDom.html('你的浏览器不支持WebSocket！');
        }

        function setOpBtn(flag) {
            if (flag) {
                $('.btn-op[op="start"]').show();
                $('.btn-op[op="stop"],.btn-op[op="restart"]').hide();
                nowStatus = false;
            } else {
                $('.btn-op[op="start"]').hide();
                $('.btn-op[op="stop"],.btn-op[op="restart"]').show();
                nowStatus = true;
            }
        }

        function scrollToBotomm() {
            var h = showLogDom[0].scrollHeight;
            if (window.screen.height * 5 < h) {
                var attr = autoClearDom.attr('checked');
                if (attr === "checked" || attr === true || attr === "true") {
                    showLogDom.html("已清空屏幕缓存" + '<br/>');
                    showLogDom.scrollTop(0);
                    return;
                }
            }
            showLogDom.scrollTop(h);
        }

        function loopLogAjax() {
            if (loopLog) {
                return;
            }
            loopLog = true;
            loopLogTime = setInterval(function () {
                reqLogSize();
            }, 30000);
        }

        function reqLogSize() {
            silentAjax({
                url: './log/logSize',
                data: {
                    id: "[[${projectInfo?.id}]]",
                    copyId: copyId
                },
                success: function (data) {
                    if (200 === data.code) {
                        if (data.data && data.data.logSize) {
                            $("#logSize").html(data.data.logSize).show();
                        }
                    } else {
                        $("#logSize").hide();
                        layer.msg(data.msg);
                    }
                }
            });
        }

        $('#export').on('click', function () {
            var url = "./log/export.html?id=[[${projectInfo?.id}]]&copyId=" + copyId;
            url = appendNodeId(url);
            layer.msg('加载中..', {
                icon: 16,
                shade: 0.2,
                time: 3000
            });
            location.href = url;
        });

        $("#logSize").on('click', function () {
            layer.confirm("确定要清空当前控制台日志文件内容吗？", {
                title: '系统提示'
            }, function (index) {
                layer.close(index);
                loadingAjax({
                    url: './log/resetLog',
                    data: {
                        id: "[[${projectInfo?.id}]]",
                        copyId: copyId
                    },
                    success: function (data) {
                        layer.msg(data.msg);
                        if (200 === data.code) {
                            // reqLogSize();
                            $("#logSize").hide();
                        }
                    },
                });
            });
        });

        $("#logBack").on('click', function () {
            layerOpen({
                type: 2,
                title: '备份列表',
                shade: 0.8,
                area: ['80%', '90%'],
                content: './log/logBack?id=[[${projectInfo?.id}]]&copyId=' + copyId
            });
        })
    }

    function refreshProjectData() {
        if (copyId && copyId.length > 0) {
            try {
                var reloadCopyTable = top.frames["manageList"].reloadCopyTable;
                reloadCopyTable && reloadCopyTable();
            } catch (e) {
            }
            return;
        }
        try {
            var reloadTable = top.frames["manageList"].reloadTable;
            reloadTable && reloadTable();
        } catch (e) {
        }
    }
</script>
</html>